package com.dyz.leetcode._08_StackAndQueue;

import java.util.ArrayDeque;

public class _227_calculate {
    public int calculate(String s) {
        ArrayDeque<Integer> numStack = new ArrayDeque<>();
        ArrayDeque<Character> str = new ArrayDeque<>();
        int num = 0;
        char[] chs = s.toCharArray();
        int i = 0;
        while(i<chs.length){
            if(chs[i]==' '){
                i++;
            }else if(chs[i]>='0' && chs[i]<='9'){
                num = num*10+(chs[i]-'0');
                i++;
            }else if(chs[i]=='-' || chs[i]=='+'){
                numStack.push(num);
                str.push(chs[i]);
                i++;
                num=0;
            }else if(chs[i]=='*' || chs[i]=='/'){
                numStack.push(num);
                num=0;
                char preSign = '*';
                if(chs[i]=='/'){
                    preSign = '/';
                }
                i++;

                while (i<chs.length && (Character.isDigit(chs[i]) || chs[i]== ' ')){
                    if(chs[i]== ' '){i++;continue;}
                    num = num*10+(chs[i]-'0');
                    i++;
                }
                num = preSign=='*'?numStack.pop()*num:numStack.pop()/num;
            }
        }
        numStack.push(num);
        int res = numStack.removeLast();
        while (!numStack.isEmpty()){
            char c = str.removeLast();
            int n1 = numStack.removeLast();
            res = c=='+'?n1+res:res-n1;
        }
        return res;
    }

    public static void main(String[] args) {
        int calculate = new _227_calculate().calculate("0-2147483647");
        System.out.println(calculate);
    }
}
